package com.googlecode.olabs.common.client.contact;

import java.util.ArrayList;
import java.util.Collection;

import com.googlecode.olabs.common.client.contact.field.Field;
import com.googlecode.olabs.common.client.contact.field.FormattedNameField;
import com.googlecode.olabs.common.client.contact.field.IdField;
import com.googlecode.olabs.common.client.contact.field.NameField;

public class ContactImpl implements Contact {

	private static final long serialVersionUID = 1L;

	private final Collection<Field> m_fields;

	public ContactImpl() {
		m_fields = new ArrayList<Field>();
	}

	public void clearFields() {
		synchronized (m_fields) {
			m_fields.clear();
		}
	}

	public void addField(Field field) {
		synchronized (m_fields) {
			m_fields.add(field);
		}
	}

	public boolean removeField(Field field) {
		synchronized (m_fields) {
			return m_fields.remove(field);
		}
	}

	public Collection<Field> getFields() {
		synchronized (m_fields) {
			return new ArrayList<Field>(m_fields);
		}
	}

	public boolean isValid() {
		synchronized (m_fields) {
			return getId() != null && getFormattedName() != null;
		}
	}

	public IdField getId() {
		for (Field field : m_fields) {
			if (field instanceof IdField) {
				return (IdField) field;
			}
		}
		return null;
	}

	public FormattedNameField getFormattedName() {
		for (Field field : m_fields) {
			if (field instanceof FormattedNameField) {
				return (FormattedNameField) field;
			}
		}
		return null;
	}

	public NameField getName() {
		for (Field field : m_fields) {
			if (field instanceof NameField) {
				return (NameField) field;
			}
		}
		return null;
	}

}
